package com.duing.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duing.common.PageResult;
import com.duing.common.ResponseResult;
import com.duing.dto.BookQueryDTO;
import com.duing.entity.Book;
import com.duing.enums.ErrorCode;
import com.duing.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/book")
public class BookController {
    @Autowired
    private BookServiceImpl bookService;

    @PostMapping("/add")
    public ResponseResult<Book> addBook(@Valid Book book) {
        bookService.validateBook(book);
        bookService.save(book);
        return ResponseResult.success(book);
    }

    @PostMapping("/delete")
    public ResponseResult<Boolean> deleteBook(@RequestParam Long id) {
        boolean res = bookService.removeById(id);
        return res ? ResponseResult.success(res) : ResponseResult.error(ErrorCode.NOT_FOUND.getCode(), "该书不存在");
    }

    @PostMapping("/update")
    public ResponseResult<Book> updateBook(@Valid Book book) {
        bookService.updateById(book);
        return ResponseResult.success(book);
    }

    @GetMapping("/{id}")
    public ResponseResult<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getById(id);
        return ResponseResult.success(book);
    }

    @GetMapping("/listByParams")
    public ResponseResult<PageResult<Book>> getBooksByKeyword(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @ModelAttribute BookQueryDTO dto
    ){
        Page<Book> bookPage = bookService.getBooksByKeyword(page, size, dto);
        PageResult<Book> pageResult = new PageResult<>(bookPage.getRecords(),bookPage.getTotal(),bookPage.getCurrent(),bookPage.getSize());
        return ResponseResult.success(pageResult);
    }
}
